package com.aiyige.model;

import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.city.model.City;
import com.aiyige.model.enums.GoodsType;
import com.aiyige.model.eshop.BuyerBackup;
import com.aiyige.model.eshop.DiscountsBackup;
import com.aiyige.model.eshop.MediaSummary;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.eshop.ProductsBackup;
import com.aiyige.model.eshop.SellerBackup;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.request.OrderStatusEnum;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by xiachao on 2017/11/17.
 */

public class OrderEntity implements Parcelable{
//    //0-待付款，1-已付款，2-已取消，3-待发货，4-待确认，5-已确认，6-申请退货，7-已退货。NOPAY{0}，NOSHIP{1,3}，UNCONFIRM{4}，AFTERSALE{6,7}
//    public static final int STATUS_0_NOPAY = 0;// 待付款
//    public static final int STATUS_1_PAYED = 1;// 已付款
//    public static final int STATUS_2_CANCEL = 2;// 已取消
//    public static final int STATUS_3_WAITING_SHIP = 3;// 待发货
//    public static final int STATUS_4_WAITING_AFFIRM = 4;// 待确认
//    public static final int STATUS_5_CONFIRMED = 5;// 已确认
//    public static final int STATUS_6_SALES_RETURN = 6;// 申请退货
//    public static final int STATUS_7_HAVE_TO_RETURN = 7;// 已退货

    public static final int STATUS_DELETED = -1;// 已删除（此状态是app自定义，当详情页，用来标记给内存列表中接收广播后进行删除用的）





    public final static String  statusRefunding = "refunding";   //退款中
    public final static String  statusRefunded = "refunded";   //已退款
    public final static String  statusRejected = "rejected";   //已驳回


    private String orderId;//用于api操作


    private String orderCode;//用于展示
    private String goodsType;
    private int status;
    private List<String> cover;
    private String title;
    private long createTime;
    private String sellerName;


    private String buyerName;


    private String buyerPhone;
    private String sellerId;
    private int sellerLevel;
    private int buyerLevel;
    private String sellerAvatar;
    private String buyerAvatar;
    private Double amount = 0.0;
    private Double payAmount;
    private int videoStages;
    private String source;
    private String sourceUrl;
    private String router;
    private String userAvatar;
    private String userName;
    private String userId;

    private boolean hasMore = false;

    private Order order;


    String statusString = "";
    SellerBackup seller;
    BuyerBackup buyer;
    List<ProductsBackup> productsBackupList;
    ProductsBackup product;
    MediaSummary mediaSummary;


    String cityName = "";

    String createTimeString;

    boolean isMyOrder = false;

    String headImageUrl;


    List<OperationModel> operationList;

    String refundId;

    String feedbackStatusString;

    private String momentId;

    // 搜索分类所需要用到的tag标签
    private String typeName;

    private PriceMoreBack priceMoreBack;

    // 是否要显示type的布局（用于搜索分类列表-SearchTypeXXXPage）
    private boolean showTypeNameLayout = false;

    private int num = 1;

    public boolean isBuyer() {
        return isBuyer;
    }

    public void setBuyer(boolean buyer) {
        isBuyer = buyer;
    }

    private boolean isBuyer = false;

    public boolean isSearch() {
        return isSearch;
    }

    public void setSearch(boolean search) {
        isSearch = search;
    }

    private boolean isSearch;
    public List<OperationModel> getOperationList() {

        if (!ListUtil.isEmpty(order.getOperations())) {
            if (operationList == null) {
                operationList = new ArrayList<>();
                for (String key : order.getOperations()) {
                    if (TextUtils.isEmpty(key)) {
                        continue;
                    }
//                    if (key.equals(OperationModel.kImmediatePay)) {
//                        operationList.add(new OperationModel(key, MyApp.getAppContext().getString(R.string.pay_now)));
//                    }
//                    else if (key.equals(OperationModel.cancelOrder)) {
//                        operationList.add(new OperationModel(key, MyApp.getAppContext().getString(R.string.order_cancel)));
//                    }
                    operationList.add(new OperationModel(key));
                }
            }

        }
        return operationList;
    }

    public void setOperationList(List<OperationModel> operationList) {
        this.operationList = operationList;
    }




    public String getHeadImageUrl() {
        headImageUrl = isBuyer()?order.getSellerBackup().getAvatar():order.getBuyerBackup().getAvatar();
        return headImageUrl;
    }

    public void setHeadImageUrl(String headImageUrl) {
        this.headImageUrl = headImageUrl;
    }


    public String getFeedbackStatusString() {
        return feedbackStatusString;
    }

    public void setFeedbackStatusString(String feedbackStatusString) {
        this.feedbackStatusString = feedbackStatusString;
    }



    public String getCreateTimeString() {
        if (order != null) {
            createTimeString = TimeUtils.dateToYYYYMMDDHHSS(order.getCreateTime());
        }
        return createTimeString;
    }

    public void setCreateTimeString(String createTimeString) {
        this.createTimeString = createTimeString;
    }

    public String getMomentId() {
        if (!ListUtil.isEmpty(productsBackupList)) {
            momentId = productsBackupList.get(0).getMomentId();
        }
        return momentId;
    }

    public void setMomentId(String momentId) {
        this.momentId = momentId;
    }




    public OrderEntity(Order order) {
        this.order = order;
        if (order != null) {
            seller = order.getSellerBackup();
            buyer = order.getBuyerBackup();
            productsBackupList = order.getProductsBackup();
        }
        if (!ListUtil.isEmpty(productsBackupList)) {
            product = productsBackupList.get(0);
            mediaSummary = product.getMediaSummary();
        }
    }

    public boolean isHasMore() {
        return hasMore;
    }

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }

    public String getBuyerUserId() {
        if (buyer != null) {
            userId = buyer.getId();
        }
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }


    public String getBuyerName() {
        if (buyer != null) {
            buyerName = buyer.getName();
        }
        return buyerName;
    }

    public void setBuyerName(String buyerName) {
        this.buyerName = buyerName;
    }

    public String getUserAvatar() {
        if (buyer != null) {
            userAvatar = buyer.getAvatar();
        }
        return userAvatar;
    }

    public void setUserAvatar(String userAvatar) {
        this.userAvatar = userAvatar;
    }


    public String getUserName() {
        if (seller != null) {
            userName = seller.getName();
        }
        return userName;
    }


    public String getBuyerPhone() {
        if (seller != null) {
            buyerPhone = seller.getTel();
        }
        return buyerPhone;
    }

    public void setBuyerPhone(String buyerPhone) {
        this.buyerPhone = buyerPhone;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }


    public String getTypeName() {
        if (product != null) {
            typeName = GoodsType.getValueByKey(product.getSubject());
        }
        return typeName;
    }

    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }



    public boolean isShowTypeNameLayout() {
        return showTypeNameLayout;
    }

    public void setShowTypeNameLayout(boolean showTypeNameLayout) {
        this.showTypeNameLayout = showTypeNameLayout;
    }


    public int getNum() {
        if (product != null) {
            num = product.getCount();
        }
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }




    public String getOrderCode() {
        if (order != null) {
            orderCode = order.getCode();
        }
        return orderCode;
    }

    public void setOrderCode(String orderCode) {
        this.orderCode = orderCode;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }


    public String getOrderId() {
        if (order != null) {
            orderId = order.getId();
        }
        return orderId;
    }

    public void setGoodsType(String goodsType) {
        this.goodsType = goodsType;
    }


    public String getGoodsType() {
        if (product != null) {
            goodsType = product.getSubject();
        }
        return goodsType;
    }

    public void setStatus(int status) {
        this.status = status;
        if (order != null) {
            order.setStatus(status);
        }
    }


    public int getStatus() {
        if (order != null) {
            status = order.getStatus();
        }
        return status;
    }

    public void setCover(List<String> cover) {
        this.cover = cover;
    }


    public List<String> getCover() {
        if (product != null && !ListUtil.isEmpty(product.getCover())) {
            cover = product.getCover();
        }
        if (cover == null) {
            cover = Arrays.asList("");
        }
        return cover;
    }

    public void setTitle(String title) {
        this.title = title;
    }


    public String getTitle() {
        if (product != null) {
            title = product.getTitle();
        }
        return TextUtils.isEmpty(title) ? "" : title;
    }

    public void setCreateTime(long createTime) {
        this.createTime = createTime;
    }


    public long getCreateTime() {
        if (order != null) {
            createTime = order.getCreateTime();
        }
        return createTime;
    }

    public void setSellerName(String sellerName) {
        this.sellerName = sellerName;
    }

    public String getSellerName() {
        if (seller != null) {
            sellerName = seller.getName();
        }
        return sellerName;
    }

    public void setSellerId(String sellerId) {
        this.sellerId = sellerId;
    }


    public String getSellerId() {
        if (seller != null) {
            sellerId = seller.getId();
        }
        return sellerId;
    }

    public void setSellerLevel(int sellerLevel) {
        this.sellerLevel = sellerLevel;
    }

    public int getSellerLevel() {
        if (seller != null) {
            sellerLevel = seller.getLevel();
        }
        return sellerLevel;
    }


    public int getBuyerLevel() {
        if (buyer != null) {
            buyerLevel = buyer.getLevel();
        }
        return buyerLevel;
    }

    public void setSellerAvatar(String sellerAvatar) {
        this.sellerAvatar = sellerAvatar;
    }

    public String getSellerAvatar() {
        if (seller != null) {
            sellerAvatar = seller.getAvatar();
        }
        return sellerAvatar;
    }


    public String getBuyerAvatar() {
        if (buyer != null) {
            buyerAvatar = buyer.getAvatar();
        }
        return buyerAvatar;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }


    /**
     * 订单总价格
     * @return
     */
    public Double getAmount() {
        if (order != null) {
            amount = order.getAmount();
        }
        return amount;
    }

    /**
     * 划线价
     * @return
     */
    public Double getLineationAmount() {
        if (order != null) {
            amount = order.getAmount();
        }
        return amount;
    }

    public void setPayAmount(Double payAmount) {
        this.payAmount = payAmount;
    }


    public Double getPayAmount() {
        if (order != null) {
            payAmount = order.getPayAmount();
        }
        return payAmount;
    }

    public void setVideoStages(int videoStages) {
        this.videoStages = videoStages;
    }


    public int getVideoStages() {
        if (mediaSummary != null) {
            videoStages = mediaSummary.getCount();
        }
        return videoStages;
    }

    public void setSource(String source) {
        this.source = source;
    }


    public String getSource() {
        if (order != null) {
            return order.getSource();
        }
        return TextUtils.isEmpty(source) ? "" : source;
    }

    public void setSourceUrl(String sourceUrl) {
        this.sourceUrl = sourceUrl;
    }



    public String getSourceUrl() {
        if (order != null) {
            return order.getSourceUrl();
        }
        return "";
    }

    public void setRouter(String router) {
        this.router = router;
    }


    public String getRouter() {
        if (!ListUtil.isEmpty(getAgreementBackup())) {
            router = getAgreementBackup().get(0).getRouter();
        }
        return TextUtils.isEmpty(router) ? "" : router;
    }



    public String getStatusString() {

        statusString = OrderStatusEnum.getValueByKey(getStatus());
        return statusString;
    }


    public String getCityName() {

        if (product != null) {
            City city = DummyDataUtil.getCityById(product.getCityId());
            if (city != null) {
                cityName = city.getCity();
            }
        }
        return cityName;
    }

    public String getMoreBackupJson() {
        if (!ListUtil.isEmpty(order.getAgreementBackup())) {
            return order.getAgreementBackup().get(0).getMoreBackup();
        }
        return null;
    }

    public String getMobile() {
        if (seller != null) {
            return seller.getTel();
        }
        return "";
    }

    /**
     * 单价
     * @return
     */
    public double getSinglePrice() {
        if (priceMoreBack == null && !TextUtils.isEmpty(getMoreBackupJson())) {
             priceMoreBack = JsonUtil.toObject(getMoreBackupJson(),PriceMoreBack.class);
        }
        if (priceMoreBack != null) {
            return priceMoreBack.getPrice();
        } else {
            return 0;
        }

    }

    public long getPayTime() {
        return order!= null  ? order.getPayTime():0;
    }

    public String getPayCode() {
        return  order != null ? order.getPayCode() : "";
    }

    public int getPayMethod() {
        return order!= null ? order.getPayMethod():0;
    }

    public String getPayMethodString() {
        if (getPayMethod() == 1 || getPayMethod() == 5) {
            return MyApp.getAppContext().getResources().getString(R.string.alipay);
        } else if (getPayMethod() == 2 || getPayMethod() == 6) {
            return MyApp.getAppContext().getResources().getString(R.string.wechat);
        }
        else if (getPayMethod() == 3) {
            return MyApp.getAppContext().getResources().getString(R.string.bank_card);
        }
        else if (getPayMethod() == 4) {
            return MyApp.getAppContext().getResources().getString(R.string.apple_pay);
        }
        return "";
    }

    public String getBuyerUserName() {
        if (buyer != null) {
            return buyer.getName();
        }
        return "";
    }

    public String getBuyerMobile() {
        if (buyer != null) {
            return buyer.getMobile();
        }
        return "";
    }

    public List<AgreementBackup> getAgreementBackup() {
        return order.getAgreementBackup();
    }

    public boolean hasConsumptionGuarantee() {
        if (order != null && !ListUtil.isEmpty(order.getAgreementBackup()) && !TextUtils.isEmpty(order.getAgreementBackup().get(0).subject)
                && order.getAgreementBackup().get(0).getSubject().equals(Subject.major_course) && !TextUtils.isEmpty(order.getAgreementBackup().get(0).getMoreBackup())) {
            try {
                MajorCourse majorCourse = JsonUtil.toObject(order.getAgreementBackup().get(0).getMoreBackup(),MajorCourse.class);
                if (majorCourse != null && majorCourse.getConsumptionGuarantee()) {
                    return true;
                }
            } catch (Exception e) {
            }
        }
        return false;
    }

    private String getStatusString(String statusKey) {
        if (TextUtils.isEmpty(statusKey)) {
            return "";
        }
        if (statusKey.equals(statusRefunding)) {
            return MyApp.getAppContext().getString(isBuyer()?R.string.refunding:R.string.after_sale);
        }
        else if (statusKey.equals(statusRefunded)) {
            return MyApp.getAppContext().getString(R.string.refunded);
        }
        else if (statusKey.equals(statusRejected)) {
            return MyApp.getAppContext().getString(isBuyer()?R.string.a_refund_was_dismissed:R.string.rejected);
        }
        return "";
    }



    public String getRefundStatusString() {
        if (order != null && !TextUtils.isEmpty(order.getRefundStatus())) {
            return getStatusString(order.getRefundStatus());
        } else {
            return "";
        }
    }

    public void setRefundId(String refundId) {
        this.refundId = refundId == null ? "" : refundId;
    }

    public String getRefundId() {
        if (order != null) {
            return order.getRefundId();
        }
        return null;
    }

    public double getUserFee() {
        if (order != null) {
            return order.getUserFee();
        }
        return 0.00;
    }

    public String getSellerAccid() {
        if (seller != null && !TextUtils.isEmpty(seller.getAccid())) {
            return seller.getAccid();
        }
        return null;
    }

    public DiscountsBackup getDiscountsBackup() {
        if (order != null && !ListUtil.isEmpty(order.getDiscountsBackup())) {
            return order.getDiscountsBackup().get(0);
        }
        return null;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.orderId);
        dest.writeString(this.orderCode);
        dest.writeString(this.goodsType);
        dest.writeInt(this.status);
        dest.writeStringList(this.cover);
        dest.writeString(this.title);
        dest.writeLong(this.createTime);
        dest.writeString(this.sellerName);
        dest.writeString(this.buyerName);
        dest.writeString(this.buyerPhone);
        dest.writeString(this.sellerId);
        dest.writeInt(this.sellerLevel);
        dest.writeInt(this.buyerLevel);
        dest.writeString(this.sellerAvatar);
        dest.writeString(this.buyerAvatar);
        dest.writeValue(this.amount);
        dest.writeValue(this.payAmount);
        dest.writeInt(this.videoStages);
        dest.writeString(this.source);
        dest.writeString(this.sourceUrl);
        dest.writeString(this.router);
        dest.writeString(this.userAvatar);
        dest.writeString(this.userName);
        dest.writeString(this.userId);
        dest.writeByte(this.hasMore ? (byte) 1 : (byte) 0);
        dest.writeParcelable(this.order, flags);
        dest.writeString(this.statusString);
        dest.writeParcelable(this.seller, flags);
        dest.writeParcelable(this.buyer, flags);
        dest.writeTypedList(this.productsBackupList);
        dest.writeParcelable(this.product, flags);
        dest.writeParcelable(this.mediaSummary, flags);
        dest.writeString(this.cityName);
        dest.writeString(this.createTimeString);
        dest.writeByte(this.isMyOrder ? (byte) 1 : (byte) 0);
        dest.writeString(this.headImageUrl);
        dest.writeList(this.operationList);
        dest.writeString(this.refundId);
        dest.writeString(this.feedbackStatusString);
        dest.writeString(this.momentId);
        dest.writeString(this.typeName);
        dest.writeByte(this.showTypeNameLayout ? (byte) 1 : (byte) 0);
        dest.writeInt(this.num);
        dest.writeByte(this.isBuyer ? (byte) 1 : (byte) 0);
    }

    protected OrderEntity(Parcel in) {
        this.orderId = in.readString();
        this.orderCode = in.readString();
        this.goodsType = in.readString();
        this.status = in.readInt();
        this.cover = in.createStringArrayList();
        this.title = in.readString();
        this.createTime = in.readLong();
        this.sellerName = in.readString();
        this.buyerName = in.readString();
        this.buyerPhone = in.readString();
        this.sellerId = in.readString();
        this.sellerLevel = in.readInt();
        this.buyerLevel = in.readInt();
        this.sellerAvatar = in.readString();
        this.buyerAvatar = in.readString();
        this.amount = (Double) in.readValue(Double.class.getClassLoader());
        this.payAmount = (Double) in.readValue(Double.class.getClassLoader());
        this.videoStages = in.readInt();
        this.source = in.readString();
        this.sourceUrl = in.readString();
        this.router = in.readString();
        this.userAvatar = in.readString();
        this.userName = in.readString();
        this.userId = in.readString();
        this.hasMore = in.readByte() != 0;
        this.order = in.readParcelable(Order.class.getClassLoader());
        this.statusString = in.readString();
        this.seller = in.readParcelable(SellerBackup.class.getClassLoader());
        this.buyer = in.readParcelable(BuyerBackup.class.getClassLoader());
        this.productsBackupList = in.createTypedArrayList(ProductsBackup.CREATOR);
        this.product = in.readParcelable(ProductsBackup.class.getClassLoader());
        this.mediaSummary = in.readParcelable(MediaSummary.class.getClassLoader());
        this.cityName = in.readString();
        this.createTimeString = in.readString();
        this.isMyOrder = in.readByte() != 0;
        this.headImageUrl = in.readString();
        this.operationList = new ArrayList<OperationModel>();
        in.readList(this.operationList, OperationModel.class.getClassLoader());
        this.refundId = in.readString();
        this.feedbackStatusString = in.readString();
        this.momentId = in.readString();
        this.typeName = in.readString();
        this.showTypeNameLayout = in.readByte() != 0;
        this.num = in.readInt();
        this.isBuyer = in.readByte() != 0;
    }

    public static final Creator<OrderEntity> CREATOR = new Creator<OrderEntity>() {
        @Override
        public OrderEntity createFromParcel(Parcel source) {
            return new OrderEntity(source);
        }

        @Override
        public OrderEntity[] newArray(int size) {
            return new OrderEntity[size];
        }
    };

    /**
     * 是否有手续费
     * @return
     */
    public boolean hasServiceCharge() {
        return getUserFee() > 0;
    }

    /**
     * 第三方平台支付手续费
     * @return
     */
    public double getServiceCharge() {
        return getUserFee();
    }

    public String getServiceChargeFrom() {
        return "（卖家承担手续费）";
    }

    public boolean hasLinePrice() {
        return !ListUtil.isEmpty(getAgreementBackup()) && getAgreementBackup().get(0).getOnsalesBackup() != null;
    }

    public double getLinePrice() {
        return getAgreementBackup().get(0).getOnsalesBackup().getPrice();
    }
}
